Download
FAQ
History
HomeHomeNext API
Search
Feedback
Divider

A J2EE Application that Uses the JMS API with an Entity Bean

This section explains how to write, compile, package, deploy, and run a J2EE application that uses the JMS API with an entity bean. The application uses the following components:

The section covers the following topics:

You will find the source files for this section in the directory <INSTALL>/j2eetutorial14/examples/jms/clientmdbentity/. Path names in this section are relative to this directory.

Overview of the Human Resources Application

This application simulates, in a simplified way, the work flow of a company's human resources (HR) department when it processes a new hire. This application also demonstrates how to use the J2EE platform to accomplish a task that many JMS client applications perform.

A JMS client must often wait for several messages from various sources. It then uses the information in all these messages to assemble a message that it then sends to another destination. The common term for this process is joining messages. Such a task must be transactional, with all the receives and the send as a single transaction. If all the messages are not received successfully, the transaction can be rolled back. For a client example that illustrates this task, see A Local Transaction Example.

A message-driven bean can process only one message at a time in a transaction. To provide the ability to join messages, a J2EE application can have the message-driven bean store the interim information in an entity bean. The entity bean can then determine whether all the information has been received; when it has, the entity bean can create and send the message to the other destination. Once it has completed its task, the entity bean can remove itself.

The basic steps of the application are as follows.

  1. The HR department's application client generates an employee ID for each new hire and then publishes a message containing the new hire's name and employee ID. The client then creates a temporary queue with a message listener that waits for a reply to the message.
  2. Two message-driven beans process each message: One bean assigns the new hire's office number, and one bean assigns the new hire's equipment. The first bean to process the message creates an entity bean to store the information it has generated. The second bean locates the existing entity bean and adds its information.
  3. When both the office and the equipment have been assigned, the entity bean sends to the reply queue a message describing the assignments, then removes itself. The application client's message listener retrieves the information.

Figure 21-3 illustrates the structure of this application. An actual HR application would have more components, of course; other beans could set up payroll and benefits records, schedule orientation, and so on.

A J2EE Application: Client to Message-Driven Beans to Entity Bean

Figure 21-3 A J2EE Application: Client to Message-Driven Beans to Entity Bean

Writing the Application Components

Writing the components of the application involves

Coding the Application Client: HumanResourceClient.java

The application client program, src/HumanResourceClient.java, performs the following steps:

  1. Uses the JNDI naming context java:comp/env to look up a ConnectionFactory and a topic
  2. Creates a TemporaryQueue to receive notification of processing that occurs, based on new-hire events it has published
  3. Creates a MessageConsumer for the TemporaryQueue, sets the MessageConsumer's message listener, and starts the connection
  4. Creates a MessageProducer and a MapMessage
  5. Creates five new employees with randomly generated names, positions, and ID numbers (in sequence) and publishes five messages containing this information

The message listener, HRListener, waits for messages that contain the assigned office and equipment for each employee. When a message arrives, the message listener displays the information received and checks to see whether all five messages have arrived yet. When they have, the message listener notifies the main program, which then exits.

Coding the Message-Driven Beans

This example uses two message-driven beans, src/ReserveEquipmentMsgBean.java and src/ReserveOfficeMsgBean.java. The beans take the following steps.

  1. The ejbCreate method gets a handle to the local home interface of the entity bean.
  2. The onMessage method retrieves the information in the message. The ReserveEquipmentMsgBean's onMessage method chooses equipment, based on the new hire's position; the ReserveOfficeMsgBean's onMessage method randomly generates an office number.
  3. After a slight delay to simulate real-world processing hitches, the onMessage method calls a helper method, compose.
  4. The compose method either creates or finds, by primary key, the SetupOffice entity bean and uses it to store the equipment or the office information in the database.

Coding the Entity Bean

The SetupOffice bean is an entity bean that uses a local interface. The local interface allows the entity bean and the message-driven beans to be packaged in the same EJB JAR file for maximum efficiency. The entity bean has these components:

The local home interface source file is src/SetupOfficeLocalHome.java. It declares the create method, called createLocal for a bean that uses a local interface, and one finder method, findByPrimaryKey.

The local interface, src/SetupOfficeLocal.java, declares several business methods that get and manipulate new-hire data.

The bean class, src/SetupOfficeBean.java, implements the business methods and their helper method, checkIfSetupComplete. The bean class also implements the required methods ejbCreateLocal, ejbPostCreateLocal, setEntityContext, unsetEntityContext, ejbRemove, ejbActivate, ejbPassivate, ejbLoad, and ejbStore. The ejbFindByPrimaryKey method is generated automatically.

The only methods called by the message-driven beans are the business methods declared in the local interface, the findByPrimaryKey method, and the createLocal method. The entity bean uses container-managed persistence, so all database calls are generated automatically.

Creating and Packaging the Application

This example uses a connection factory named jms/TopicConnectionFactory and a topic named jms/Topic, both of which you probably created in the previous chapter. If not, see Creating the JMS Administered Objects for the Simple Examples for instructions.

Creating and packaging this application involve several steps:

Starting the PointBase Database Server

The PointBase software is included with the J2EE Application Server download bundle. You may also run this example with databases provided by other vendors.

The PointBase server should be started before you start the J2EE Application Server. If the J2EE Application Server is running, stop it as follows:

From the command line prompt, start the PointBase database server.

Compiling the Source Files and Starting the J2EE Application Server

  1. Use the build target to compile the source files:
  2. asant build

  3. Start the J2EE Application Server.

Creating Database Resources

In order to use entity beans that use container-managed persistence with the J2EE Application Server, you must create a JDBC connection pool, a JDBC resource, and a persistence resource. The tutorial provides asant targets for all of these. The first two targets are in the file <INSTALL>/j2eetutorial14/examples/common/targets.xml. The last one is in the file <INSTALL>/j2eetutorial14/examples/jms/clientmdbentity/build.xml. Perform the following steps:

  1. Create a JDBC connection pool named ejb-tutorial-pool:
  2. asant create-jdbc-connection-pool_common

  3. Create a JDBC resource named jdbc/ejbTutorialDB:
  4. asant create-jdbc-resource_common

  5. Create a persistence resource named jdo/cmp-clientmdbentity:
  6. asant create-persistence-resource

  7. Reconfigure the server:
  8. asant reconfig_common

Starting the J2EE Deploytool and Creating the Application

  1. Start the deploytool.
  2. Choose FileRight ArrowNewRight ArrowApplication EAR.
  3. Click Browse next to the Application File Name field and use the file chooser to locate the directory clientmdbentity.
  4. In the File Name field, type ClientMDBEntityApp.
  5. Click New Application.
  6. Click OK.

Packaging the Application Client

To package the application client, perform the following steps:

  1. Choose FileRight ArrowNewRight ArrowApplication Client JAR to start the Application Client Wizard.
  2. In the JAR File Contents screen:
    1. Verify that Create New AppClient Module in Application is selected and that the application is ClientMDBEntityApp.
    2. In the AppClient Display Name field, type HumanResourceClient.
    3. Click the Edit button next to the Contents text area.
    4. In the dialog box, locate the build/client/ directory. Select HumanResourceClient.class and HumanResourceClient$HRListener.class from the Available Files tree area and click Add, then OK.
  3. In the General screen, select client.HumanResourceClient in the Main Class combo box.
  4. In the Message Destination References screen, click Add. In the dialog box:
    1. Type jms/NewHireTopic in the Coded Name field.
    2. Choose javax.jms.Topic from the Destination Type menu.
    3. Choose Produces from the Usage menu.
    4. Type PhysicalTopic in the Destination Name field.
  5. In the Resource References screen:
    1. Click Add.
    2. Type jms/MyConnectionFactory in the Coded Name field.
    3. Choose javax.jms.ConnectionFactory from the Type menu.
    4. Type jms/TopicConnectionFactory in the JNDI name field and j2ee in both the User Name and Password fields.
  6. Click Finish.
  7. Click the Message Destinations tab. In the inspector pane:
    1. Click Add.
    2. Type PhysicalTopic in the Destination Name field. When you press Enter, this name appears in the Display Name field, and HumanResourceClient appears in the Producers area.
    3. Type jms/Topic in the JNDI Name field.

Packaging the Message-Driven Beans

Follow these instructions twice, first for the Equipment message-driven bean and then for the Office message-driven bean.

  1. Choose FileRight ArrowNewRight ArrowEnterprise JavaBean JAR to start the Enterprise Bean Wizard, then click Next.
  2. In the EJB JAR screen:
    1. Select Create New JAR Module in Application and verify that the application is ClientMDBEntityApp. The second time, choose Add to Existing JAR Module.
    2. In the JAR Display Name field, type EBJAR. (You only do this the first time.)
    3. Click the Edit button next to the Contents text area.
    4. In the dialog box, locate the build/eb/ directory. Select ReserveEquipmentMsgBean.class from the Available Files tree area and click Add, then OK. (The second time, choose ReserveOfficeMsgBean.class.)
  3. In the General screen:
    1. Choose the Message-Driven radio button.
    2. From the Enterprise Bean Class menu, choose eb.ReserveEquipmentMsgBean (the second time, choose eb.ReserveOfficeMsgBean).
    3. In the Enterprise Bean Display Name field, type EquipmentMDB (the second time, type OfficeMDB).
  4. In the Configuration Options screen, check the Enterprise Bean References and Transaction Management boxes.
  5. In the Message-Driven Bean Settings screen:
    1. Click Add in the Activation Configuration Properties area.
    2. Type destination in the Property Name field and PhysicalTopic in the Value field.
    3. Click Add again.
    4. Type destinationType in the Property Name field and javax.jms.Topic in the Value field.
    5. Choose javax.jms.Topic from the Destination Type menu.
    6. Type PhysicalTopic in the Destination Name field.
    7. Click Deployment Settings. In the dialog box, type jmsra in the Resource Adapter field and click OK.
  6. In the Transaction Management screen, choose Container-Managed.
  7. In the Enterprise Bean References screen, click Add. In the dialog box:
    1. Type ejb/local/SetupOffice in the Coded Name field.
    2. Choose Entity from the EJB Type menu.
    3. Choose Local from the Interfaces menu.
    4. Type eb.SetupOfficeLocalHome in the Home Interface field.
    5. Type eb.SetupOfficeLocal in the Local/Remote Interface field.
    6. Type SetupOffice in the Enterprise Bean Name field.
    7. The entity bean uses local interfaces, so the message-driven beans access the bean through the bean name rather than the JNDI name.

Packaging the Entity Bean

To package the entity bean, perform the following steps:

  1. Choose FileRight ArrowNewRight ArrowEnterprise JavaBean JAR to start the Enterprise Bean Wizard, then click Next.
  2. In the EJB JAR screen:
    1. Choose Add to Existing JAR Module and verify that the module is EBJAR (ClientMDBEntityApp).
    2. Click the Edit button next to the Contents text area.
    3. In the dialog box, locate the build/eb/ directory. Select SetupOfficeBean.class, SetupOfficeLocal.class, and SetupOfficeLocalHome.class from the Available Files tree area and click Add, then OK.
  3. In the General screen:
    1. Choose the Entity radio button.
    2. From the Enterprise Bean Class menu, choose eb.SetupOfficeBean.
    3. In the Enterprise Bean Display Name field, type SetupOffice.
    4. In the Local Interfaces area, choose eb.SetupOfficeLocalHome from the Local Home Interface menu and eb.SetupOfficeLocal from the Local Interface menu.
  4. In the Configuration Options screen, check the Resource References and Transaction Management boxes.
  5. In the Entity Settings screen:
    1. Select the radio button labeled Container-Managed Persistence (2.0).
    2. Select the checkboxes next to all six fields in the Fields To Be Persisted area: employeeId, employeeName, equipmentList, officeNumber, serializedReplyDestination, and replyCorrelationMsgId.
    3. In the Abstract Schema Name field, type SetupOfficeSchema.
    4. In the Primary Key Class field, type java.lang.String.
    5. In the Primary Key Field Name field, select employeeId.
  6. In the Transaction Management screen, choose Container-Managed.
  7. In the Resource References screen:
    1. Click Add.
    2. Type jms/MyConnectionFactory in the Coded Name field.
    3. Choose javax.jms.ConnectionFactory from the Type menu.
    4. Type jms/TopicConnectionFactory in the JNDI name field and j2ee in both the User Name and Password fields.

You don't need to specify any message destinations for this bean, because the bean uses a temporary destination for the reply message.

Now, specify the message destinations for the enterprise bean JAR file. Click the EBJAR node, then click the Message Destinations tab. In the inspector pane:

  1. Click Add.
  2. Type PhysicalTopic in the Destination Name field. When you press Enter, this name appears in the Display Name field, HumanResourceClient appears in the Producers area, and the names of the message-driven beans appear in the Consumers area.
  3. Type jms/Topic in the JNDI Name field.

Now, specify the CMP resources for the bean.

  1. Click the Cmp Resource tab.
  2. In the Jndi Name field, type jdo/cmp-clientmdbentity.
  3. In the Database Table combo box, select the two checkboxes labeled Create table on deploy and Delete table on undeploy.
  4. Choose pointbase from the Vendor Name menu.

Updating the JNDI Names

In the J2EE Application Server, the JNDI name for a message-driven bean is the destination it receives messages from, not the bean name.

  1. Select the application and click the JNDI Names tab.
  2. Type jms/Topic in the JNDI Name field for both EquipmentMDB and OfficeMDB.

Leave the JNDI Name field for the EJB references empty, because you are accessing the entity bean through a local interface.

Verify that the JNDI names for the application components are correct. They should appear as shown in Table 21-6 and Table 21-7.

Table 21-6 Application Pane for ClientMDBEntityApp
Component Type
Component
JNDI Name
EJB
EquipmentMDB
jms/Topic
EJB
OfficeMDB
jms/Topic
EJB
SetupOffice
SetupOffice

Table 21-7 References Pane for ClientMDBEntityApp
Ref. Type
Referenced By
Reference Name
JNDI Name
EJB Ref
EquipmentMDB
ejb/local/SetupOffice
 
EJB Ref
OfficeMDB
ejb/local/SetupOffice
 
Resource
HumanResourceClient
jms/MyConnectionFactory
jms/TopicConnectionFactory
Resource
SetupOffice
jms/MyConnectionFactory
jms/TopicConnectionFactory

Deploying the Application

  1. Choose FileRight ArrowSave to save the application.
  2. Choose ToolsRight ArrowDeploy.
  3. In the dialog box, type your administrative user name and password (if they are not already filled in) and click OK.
  4. In the Distribute Module dialog box, click Close when the process completes.

Saving the Client JAR and Running the Application

  1. In the deploytool, select the server node.
  2. Select ClientMDBEntityApp from the list of deployed objects, then click Client Jar.
  3. Choose Browse to navigate to the directory from which you will run the client. Specify the clientmdbentity directory. When you reach the directory, click Select, then click OK. Click OK in the information dialog. You will find a file named ClientMDBEntityAppClient.jar in the specified directory.
  4. To run the client, use the following command:
  5. appclient -client ClientMDBEntityAppClient.jar

The program output in the terminal window looks something like this:

INFO: Binding name:`java:comp/env/jms/NewHireTopic`
PUBLISHER: Setting hire ID to 25, name Gertrude Bourbon, 
position Senior Programmer
PUBLISHER: Setting hire ID to 26, name Jack Verdon, position 
Manager
PUBLISHER: Setting hire ID to 27, name Fred Tudor, position 
Manager
PUBLISHER: Setting hire ID to 28, name Fred Martin, position 
Programmer
PUBLISHER: Setting hire ID to 29, name Mary Stuart, position 
Manager
Waiting for 5 message(s)
New hire event processed:
  Employee ID: 25
  Name: Gertrude Bourbon
  Equipment: Laptop
  Office number: 183
Waiting for 4 message(s)
New hire event processed:
  Employee ID: 26
  Name: Jack Verdon
  Equipment: Pager
  Office number: 20
Waiting for 3 message(s)
New hire event processed:
  Employee ID: 27
  Name: Fred Tudor
  Equipment: Pager
  Office number: 51
Waiting for 2 message(s)
New hire event processed:
  Employee ID: 28
  Name: Fred Martin
  Equipment: Desktop System
  Office number: 141
Waiting for 1 message(s)
New hire event processed:
  Employee ID: 29
  Name: Mary Stuart
  Equipment: Pager
  Office number: 238 

The output from the enterprise beans appears in the server log. For each employee, the application first creates the entity bean, then finds it. You may see runtime errors in the server log about transactions and primary keys, and transaction rollbacks may occur. The fact that the client runs correctly in spite of these errors is one of the advantages of container-managed transactions.

Undeploying and Removing the Application

To undeploy and remove the application, perform the following steps:

  1. Select the deployed application in the server pane and click Undeploy.
  2. Select the application in the left-hand pane and choose FileRight ArrowClose.
  3. Remove the build directory:
  4. asant clean

  5. If you wish, stop the server:
  6. asadmin stop-domain

If you wish, you can manually delete the EAR and client JAR files.

Divider
Download
FAQ
History
HomeHomeNext API
Search
Feedback
Divider

All of the material in The J2EE 1.4 Tutorial is copyright-protected and may not be published in other works without express written permission from Sun Microsystems.